package com.seven.sevenchat.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.seven.sevenchat.VO.UserVO;
import com.seven.sevenchat.common.ErrorCode;
import com.seven.sevenchat.contant.UserConstant;
import com.seven.sevenchat.exception.BusinessException;
import com.seven.sevenchat.model.User;
import com.seven.sevenchat.service.UserService;
import com.seven.sevenchat.mapper.UserMapper;
import com.seven.sevenchat.utils.AlgorithmUtils;

import org.springframework.data.domain.Sort;
import org.springframework.data.geo.Point;
import org.apache.commons.math3.util.Pair;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.GeoResult;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import static com.seven.sevenchat.contant.UserConstant.ADMIN_ROLE;
import static com.seven.sevenchat.contant.UserConstant.ULS;

/**
* @author Dell
* @description 针对表【user】的数据库操作Service实现
* @createDate 2024-12-12 20:58:33
*/
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService{

    @Resource
    private UserMapper userMapper;
    private UserService userService;
    private StringRedisTemplate stringRedisTemplate;
    private UserConstant userConstant;
    public static final String SALT = "seven";//盐值，用于加密解密


    /**
     * 用户注册
     *
     * @param userName 用户账号
     * @param userPassword 用户密码
     * @param checkPassword 确认密码
     * @param planetCode
     * @return 新用户id
     */
    @Override
    public long userRegister(String userName, String userPassword, String checkPassword,String planetCode) {
        //  账密不空，账≥4位，密≥8位
        if(StringUtils.isAnyBlank(userName,userPassword,checkPassword,planetCode)) throw new BusinessException(ErrorCode.PARAMS_ERROR,"参数为空");
        if(userName.length()<4) throw new BusinessException(ErrorCode.PARAMS_ERROR,"用户名太短");
        if(userPassword.length()<8) throw new BusinessException(ErrorCode.PARAMS_ERROR,"密码太短");
        if(checkPassword.length()<8) throw new BusinessException(ErrorCode.PARAMS_ERROR,"密码太短");
        if(planetCode.length()>5) throw new BusinessException(ErrorCode.PARAMS_ERROR,"星球编号太长");
        //  账无字符
        String vp="[`~!@#$%^&*()+=|{}':;',\\\\[\\\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        Matcher matcher = Pattern.compile(vp).matcher(userName);
        if(matcher.find()) throw new BusinessException(ErrorCode.PARAMS_ERROR,"账号有特殊字符");
        //  账不重
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",userName);
        long count = this.count(queryWrapper);
        if(count>0) throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号重复");
        //  星球编号不重
        queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("planetCode",planetCode);
        count = this.count(queryWrapper);
        if(count>0) throw new BusinessException(ErrorCode.PARAMS_ERROR, "星球编号重复");
        //  确认密码与原密码相同
        if(!userPassword.equals(checkPassword)) throw new BusinessException(ErrorCode.PARAMS_ERROR, "确认密码不同");
        //加密
        String newPwd = DigestUtils.md5DigestAsHex((SALT+userPassword).getBytes());
        //插入
        User user = new User();
        user.setUsername(userName);
        user.setPassword(newPwd);
        user.setPlanetCode(planetCode);
        log.info(userName,newPwd,planetCode);
        boolean saveResult = this.save(user);
        if(!saveResult) throw new BusinessException(ErrorCode.SYSTEM_ERROR, "注册失败");;
        return user.getId();
    }

    /**
     * 用户登录
     *
     * @param userName     用户账号
     * @param userPassword 用户密码
     * @param request 请求
     * @return 脱敏后的用户信息
     */
    @Override
    public User userLogin(String userName, String userPassword, HttpServletRequest request) {
        //账密不空，账≥4位，密≥8位
        if(StringUtils.isAnyBlank(userName,userPassword))
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        if(userName.length()<4)
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户账号过短");
        if(userPassword.length()<8)
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户密码过短");
        //账无字符
        String vp="[`~!@#$%^&*()+=|{}':;',\\\\[\\\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        Matcher matcher = Pattern.compile(vp).matcher(userName);
        if(matcher.find())
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户名有特殊字符");
        //加密
        String newPwd = DigestUtils.md5DigestAsHex((SALT+userPassword).getBytes());
        //查询
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",userName);
        queryWrapper.eq("password",newPwd);
        User user = userMapper.selectOne(queryWrapper);
        log.info(userName);log.info(newPwd);
        if(user==null) {
            log.info("user login failed!");
            return null;
        }
        //用户脱敏[见下侧]
        User safetyUser = getSafetyUser(user);
        //记录用户登录态
        request.getSession().setAttribute(ULS,safetyUser);
        return safetyUser;
    }

    /**
     * 用户注销
     *
     * @param request
     * @return
     */
    @Override
    public Integer userLogout(HttpServletRequest request) {
        request.getSession().removeAttribute(ULS);
        log.info("user logout!");
        return 0;
    }

    /**
     * 用户脱敏
     *
     * @param user
     * @return
     */
    @Override
    public User getSafetyUser(User user) {
        if(user==null) return null;
        User safetyUser = new User();
        safetyUser.setId(user.getId());
        safetyUser.setUsername(user.getUsername());
        safetyUser.setPhoto(user.getPhoto());
        safetyUser.setGender(user.getGender());
        safetyUser.setPassword(user.getPassword());
        safetyUser.setPhone(user.getPhone());
        safetyUser.setEmail(user.getEmail());
        safetyUser.setUserStatus(user.getUserStatus());
        safetyUser.setCreateTime(user.getCreateTime());
        safetyUser.setUpdateTime(user.getUpdateTime());
        safetyUser.setIsDelete(user.getIsDelete());
        safetyUser.setRole(user.getRole());
        safetyUser.setPlanetCode(user.getPlanetCode());
        safetyUser.setTag(user.getTag());
        safetyUser.setLatitude(user.getLatitude());
        safetyUser.setLongitude(user.getLongitude());
        return safetyUser;
    }

    /**
     *   根据标签搜索用户
     * @param tagNameList  用户要搜索的标签
     * @return
     */
    @Override
    public List<User> searchUsersByTags(List<String> tagNameList){
        //1.看tagNameList是否为空
        if (CollectionUtils.isEmpty(tagNameList)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long startTime=System.currentTimeMillis();//TIME
        //2.注入like '%Java%' and like '%C++%'的数据
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        for (String tagList : tagNameList) {
            queryWrapper = queryWrapper.like("tag", tagList);
        }
        //3.数据脱敏
        List<User> userList = userMapper.selectList(queryWrapper);
        log.info("时间：sql query time:"+(System.currentTimeMillis()-startTime));//TIME
        return  userList.stream().map(this::getSafetyUser).collect(Collectors.toList());
    }

    /**
     *   根据标签搜索用户（方法2）
     * @param tagNameList  用户要搜索的标签
     * @return
     */
    @Override
    public List<User> searchUsersByTags2(List<String> tagNameList){
        //1.看tagNameList是否为空
        if (CollectionUtils.isEmpty(tagNameList)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        //2.查询所有用户
        QueryWrapper queryWrapper = new QueryWrapper<>();
        long startTime2=System.currentTimeMillis();//TIME
        List<User> userList = userMapper.selectList(queryWrapper);
        Gson gson = new Gson();
        //3.通过序列化，把Java对象转化为Json，判断内存中是否包含要求的标签
        userList.stream().filter(user -> {
            String tagstr = user.getTag();
            if (StringUtils.isBlank(tagstr)){return false;}
            //序列化
            Set<String> tempTagNameSet =  gson.fromJson(tagstr,new TypeToken<Set<String>>(){}.getType());
            //判断内存中是否包含要求的标签
            for (String tagName : tagNameList){
                if (!tempTagNameSet.contains(tagName)){return false; }
            }
            return true;
        }).map(this::getSafetyUser).collect(Collectors.toList());
        log.info("时间：memory query time:"+(System.currentTimeMillis()-startTime2));//TIME
        return userList;
    }

    /**
     * 更新用户信息
     * @param user
     * @param loginUser
     * @return
     */
    @Override
    public int updateUser(User user, User loginUser)
    {
        long userId=user.getId();
        if(userId <= 0){throw new BusinessException(ErrorCode.PARAMS_ERROR);}
        //是管理员：可更新任意用户
        //不是管理员：只可更新自己的信息
        if(!isAdmin(loginUser)){
            throw new BusinessException(ErrorCode.NO_AUTH);
        }
        if(userId == loginUser.getId()){
            throw new BusinessException(ErrorCode.NO_AUTH);
        }
        User userold=userMapper.selectById(userId);
        if(userold==null){throw new BusinessException(ErrorCode.NULL_ERROR);}
        return userMapper.updateById(user);
    }



    /**
     * 是否为管理员
     * @param request
     * @return
     */
    public boolean isAdmin(HttpServletRequest request){
        //仅管理员可查询
        Object userObj = request.getSession().getAttribute(ULS);
        User user = (User)userObj;
//        log.info(user.getUsername());
//        log.info(user.getPassword());
//        log.info(user.getEmail());
//        log.info(String.valueOf(user.getRole()));
        if(user.getUsername()==null){throw new BusinessException(ErrorCode.NOT_LOGIN);}
        return user != null && user.getRole() == ADMIN_ROLE;
    }

    /**
     * 是否为管理员
     * @param loginUser
     * @return
     */
    public boolean isAdmin(User loginUser){
        log.info(String.valueOf(loginUser.getRole()));
        if(loginUser.getRole()==null){return false;}
        return loginUser != null && loginUser.getRole() == ADMIN_ROLE;
    }

    /**
     * 推荐匹配用户
     * @param num
     * @param loginUser
     * @return
     */
    @Override
    public List<User> matchUsers(long num, User loginUser) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.isNotNull("tag");//过滤掉标签为空的用户
        queryWrapper.select("id","tag");//只查id和tag两列，提升性能
        List<User> userList = this.list(queryWrapper);
        String tags = loginUser.getTag();
        Gson gson = new Gson();
        List<String> tagList = gson.fromJson(tags, new TypeToken<List<String>>() {}.getType());
        // list映射：用户列表的下标 => 相似度
        List<Pair<User,Long>> list = new ArrayList<>();
        // 计算当前用户和所有用户的相似度
        for (int i = 0; i <userList.size(); i++) {
            User user = userList.get(i);
            String userTags = user.getTag();
            //无标签的或自己的：要过滤
            if (StringUtils.isBlank(userTags)||user.getId()==loginUser.getId())
            {
                continue;
            }
            List<String> userTagList = gson.fromJson(userTags, new TypeToken<List<String>>() {}.getType());
            //计算分数distance，并注入list映射：用户列表的下标 => 相似
            long distance = AlgorithmUtils.minDistance(tagList, userTagList);
            list.add(new Pair<>(user,distance));
        }
        //按编辑距离从小到大排序
        List<Pair<User, Long>> topUserPairList = list.stream()
                .sorted((a, b) -> (int) (a.getValue() - b.getValue()))
                .limit(num)
                .collect(Collectors.toList());
        //有顺序的userID列表
        List<Long> userListVo = topUserPairList.stream().map(pari -> pari.getKey().getId()).collect(Collectors.toList());

        //根据id查询user完整信息
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.in("id",userListVo);
        Map<Long, List<User>> userIdUserListMap = this.list(userQueryWrapper).stream()
                .map(user -> getSafetyUser(user))
                .collect(Collectors.groupingBy(User::getId));

        // 因为上面查询打乱了顺序，这里根据上面有序的userID列表赋值
        List<User> finalUserList = new ArrayList<>();
        for (Long userId : userListVo){finalUserList.add(userIdUserListMap.get(userId).get(0));}
        return finalUserList;
    }


    /**
     * 从request中，获取当前用户信息
     * @param request
     * @return
     */
    @Override
    public User getLogininUser(HttpServletRequest request){
        if(request==null) return null;
        Object userObj = request.getSession().getAttribute(ULS);
        if(userObj==null) throw new BusinessException(ErrorCode.NO_AUTH);
        return (User)userObj;
    }

    /**
     * 把经度与纬度都不为空的用户插入到redis GEO 中
     */
    @Override
    public void geoAddUser() {
        System.out.println("geoAddUser");
        //1.查询所有用户
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.isNotNull("longitude");
        userQueryWrapper.isNotNull("latitude");
        List<User> userList = userService.list(userQueryWrapper);

        //2.将 经度与纬度都不为空的用户插入到redis GEO 中
        if (userList == null){
            return;
        }
        List<RedisGeoCommands.GeoLocation<String>> locationList = new ArrayList<>(userList.size());
        for (User user : userList) {
            long id = user.getId();
            //long类型转化为String
            String idStr = String.valueOf(id);
            Point point = new Point(user.getLongitude(), user.getLatitude());
            RedisGeoCommands.GeoLocation<String> location = new RedisGeoCommands.GeoLocation<>(idStr, point);
            locationList.add(location);
        }
        stringRedisTemplate.opsForGeo().add(UserConstant.REDIS_GEO_KEY, locationList);
    }

    @Override
    public List<UserVO> searchNearUser(Integer radius, HttpServletRequest request) {

        User loginUser = getLogininUser(request);

        if (loginUser == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        //创建距离
        Distance distance = new Distance(radius, RedisGeoCommands.DistanceUnit.KILOMETERS);

        //创建参数
        RedisGeoCommands.GeoRadiusCommandArgs geoRadiusCommandArgs = RedisGeoCommands.GeoRadiusCommandArgs.newGeoRadiusArgs().includeCoordinates().includeDistance().sort(Sort.Direction.ASC);

        //进行计算
        GeoResults<RedisGeoCommands.GeoLocation<String>> geoResults = stringRedisTemplate.opsForGeo().radius(UserConstant.REDIS_GEO_KEY,
                String.valueOf(loginUser.getId()), distance, geoRadiusCommandArgs);

        //遍历数据
        List<GeoResult<RedisGeoCommands.GeoLocation<String>>> content = geoResults.getContent();

        List<UserVO> userVos = new ArrayList<>(content.size());

        for (GeoResult<RedisGeoCommands.GeoLocation<String>> result : content) {
            RedisGeoCommands.GeoLocation<String> location = result.getContent();
            String id = location.getName();
            User user = getById(Long.valueOf(id));
            UserVO userVO = new UserVO();
            BeanUtils.copyProperties(user, userVO);
            userVO.setDistance(result.getDistance().getValue());
            userVos.add(userVO);
        }

        return userVos;
    }

}




